﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 九_多线程爬虫
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            listResults.Items.Clear();
            string keyword = txtKeyword.Text.Trim();

            if (string.IsNullOrEmpty(keyword))
            {
                MessageBox.Show("Please enter a keyword.");
                return;
            }

            // 使用Task和异步编程简化线程管理
            await Task.Run(() => StartCrawling(keyword));

        }
        private void StartCrawling(string keyword)
        {
            HttpClient client = new HttpClient();
            try
            {
                // 对关键字进行URL编码
                string encodedKeyword = System.Net.WebUtility.UrlEncode(keyword);
                var response = client.GetAsync("https://mp.weixin.qq.com/s?__biz=Mzg5MjUzNzY0MA==&mid=2247560359&idx=6&sn=782ce1282c1021bb203375a23329afe4&chksm=c03f32e0f748bbf694c2c278f24ddfbba0a1c5475dcd1dd6257644d8f355d7870f5fc91195c7&scene=27" + encodedKeyword).Result;

                if (response.IsSuccessStatusCode)
                {
                    var content = response.Content.ReadAsStringAsync().Result;
                    // 这里的正则表达式用于匹配中国大陆的常见电话格式
                    var matches = Regex.Matches(content, @"(\(\d{3,4}\)|\d{3,4}-?)?\d{7,8}");

                    foreach (Match match in matches)
                    {
                        string phoneNumber = match.Value;
                        if (!listResults.Items.Contains(phoneNumber))
                        {
                            this.Invoke((MethodInvoker)delegate {
                                listResults.Items.Add(phoneNumber + " - " + response.RequestMessage.RequestUri.AbsoluteUri);
                            });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error occurred: " + ex.Message);
            }
        }

    }
}
